package com.ld.security.common.shiro.util;

import com.ld.security.common.core.exception.SuperException;
import com.ld.security.common.core.util.JsonUtil;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.HashMap;
import java.util.Set;


public class ValidationUtil {
	
	private static  final Validator validator;

	static {
		//校验工厂
		ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
		//获得检验实例
		validator = vf.getValidator();
	}
	
	public static Set<ConstraintViolation<Object>>  validate(Object obj) {
		Set<ConstraintViolation<Object>> set = validator.validate(obj);
		return set;
	}
	
	public static void validateThrow(Object obj) {
		Set<ConstraintViolation<Object>> violations= ValidationUtil.validate(obj);
		if(violations.size() > 0) {
			HashMap<String,Object> map =new HashMap<>();
			for(ConstraintViolation<Object> vi:violations) {
				map.put(vi.getPropertyPath().toString(), vi.getMessage());
			}
			throw new SuperException(JsonUtil.toJson(map));
		}
	}

}
